//
//  WHOpenPDFVC.m
//  WHEasyBizLink
//
//  Created by hyf on 2024/11/28.
//

#import "WHOpenPDFVC.h"
#import "PDFKit/PDFKit.h"


@interface WHOpenPDFVC ()<PDFViewDelegate, PDFDocumentDelegate,UIPrintInteractionControllerDelegate>
@property (nonatomic,strong)NSString *filePath;
@property (nonatomic,strong)PDFView *pdfView;
@property (nonatomic, strong) UILabel * indicatorLabel;
@property (nonatomic, strong) UIBarButtonItem * rightItem;
@end

@implementation WHOpenPDFVC

- (instancetype)initWithFilePath:(NSString *)filePath
{
    self = [super init];
    if (self) {
        self.filePath = filePath;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.title = @"预览";
    self.view.frame = CGRectMake(0,navHeight1,ScreenW,ScreenH);
    self.navigationItem.rightBarButtonItem =self.rightItem;
    [self setPdfView];
}

-(void)setPdfView{
    // 预览PDF的容器视图
    self.pdfView = [[PDFView alloc] initWithFrame:self.view.bounds];
    // 设置每一页的内边距
    self.pdfView.pageBreakMargins = UIEdgeInsetsMake(5, 30, 0, 30);
    // 设置代理
    self.pdfView.delegate = self;
    // 设置自动适配
    self.pdfView.autoScales = YES;
    [self.view addSubview:self.pdfView];
    
    // 指示器
    self.indicatorLabel = [[UILabel alloc] init];
    self.indicatorLabel.frame = CGRectMake(30, self.view.frame.size.height-50, 70, 30);
    self.indicatorLabel.layer.cornerRadius = 5;
    self.indicatorLabel.layer.masksToBounds = YES;
    self.indicatorLabel.font = [UIFont systemFontOfSize:15];
    self.indicatorLabel.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.3f];
    self.indicatorLabel.textColor = [UIColor whiteColor];
    self.indicatorLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.indicatorLabel];
    
    // 添加监听
    [self addObservers];
    
    // 创建文件
    PDFDocument *document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:self.filePath]];
    self.pdfView.document = document;
}

#pragma mark -- observer --
- (void)addObservers {
    
    kWeakSelf;
    [[NSNotificationCenter defaultCenter] addObserverForName:PDFViewPageChangedNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        weakSelf.indicatorLabel.text = [NSString stringWithFormat:@"%ld / %ld", [self getCurrentPageIndex], [self getTotalPageCount]];
    }];
}

#pragma mark -- function --
/** 获取当前PDF页面下标*/
- (NSInteger)getCurrentPageIndex {
    return self.pdfView.currentPage.label.integerValue;
}
/** 获取PDF总页数*/
- (NSInteger)getTotalPageCount {
    return self.pdfView.document.pageCount;
}


-(void)printAction {
   UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
   NSMutableArray *tempMarr = [NSMutableArray arrayWithCapacity:0];
   NSData *pdfData = [NSData dataWithContentsOfFile:self.filePath];
   if (!pdfData) {
       NSLog(@"file not exist");
       return;
   }
   [tempMarr addObject:pdfData];

   // 打印图片,与PDF不能同时打印

   if (print) {
       UIPrintInfo *printInfo = [UIPrintInfo printInfo];
       // 打印输出类型
//        printInfo.outputType = UIPrintInfoOutputPhoto;
       printInfo.outputType = UIPrintInfoOutputGeneral;
       // 默认应用程序名称
       printInfo.jobName = @"PDF";
       // 双面打印信息,NONE为禁止双面
       printInfo.duplex = UIPrintInfoDuplexLongEdge;
       // 打印纵向还是横向
       printInfo.orientation = UIPrintInfoOrientationPortrait;
       print.printInfo = printInfo;

       print.delegate = self;
//        print.showsPageRange = YES;
       print.printingItems = tempMarr;

       void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
           if (completed) {
               NSLog(@"打印完成");
           }else {
               NSLog(@"打印取消");
           }
           if (error) {
               NSLog(@"打印出错");
           }
       };
       if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
           [print presentFromRect:self.view.frame inView:self.view animated:YES completionHandler:completionHandler];
       } else {
           self.modalPresentationStyle = UIModalPresentationFullScreen;
           [print presentAnimated:YES completionHandler:completionHandler];
       }
   }
}

-(UIBarButtonItem *)rightItem
{
    if (!_rightItem)
    {
        UIButton* rightBtn= [[UIButton alloc] initWithFrame:CGRectMake(0,0,25,25)];
      [rightBtn addTarget:self action:@selector(printAction)forControlEvents:UIControlEventTouchUpInside];
        [rightBtn setBackgroundImage:[UIImage imageNamed:@"print"] forState:UIControlStateNormal];
        _rightItem =[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    }
    return _rightItem;
}
#pragma mark -- dealloc --
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

 

@end
